<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>房源管理系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            width: 80%;
            margin: 0 auto;
            padding-top: 20px;
        }
        .form-container, .house-list-container {
            margin-bottom: 30px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid #ddd;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button.delete {
            background-color: red;
        }
        .pagination {
            text-align: center;
            margin-top: 20px;
        }
        .pagination button {
            padding: 5px 10px;
            margin: 0 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>

<div class="container">
    <h1>房源管理系统</h1>

    <!-- 添加房源表单 -->
    <div class="form-container">
        <h2 id="formTitle">添加房源</h2>
        <form id="addHouseForm">
            <input type="hidden" id="houseId"> <!-- 用于保存编辑时的房源ID -->
            <label for="title">标题</label>
            <input type="text" id="title" name="title" required><br><br>

            <label for="rooms">房间数</label>
            <input type="number" id="rooms" name="rooms" required><br><br>

            <label for="area">面积 (平方米)</label>
            <input type="number" id="area" name="area" required><br><br>

            <label for="price">价格</label>
            <input type="number" id="price" name="price" required><br><br>

            <label for="address">地址</label>
            <input type="text" id="address" name="address" required><br><br>

            <button type="submit">添加房源</button>
        </form>
    </div>

    <!-- 房源列表 -->
    <div class="house-list-container">
        <h2>房源列表</h2>
        <table id="houseList">
            <thead>
            <tr>
                <th>ID</th>
                <th>标题</th>
                <th>房间数</th>
                <th>面积</th>
                <th>价格</th>
                <th>地址</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- 动态填充房源数据 -->
            </tbody>
        </table>
    </div>

    <!-- 分页按钮 -->
    <div class="pagination" id="pagination"></div>

</div>

<script>
    let currentPage = 1;
    const pageSize = 10;

    // 获取房源列表
    function getHouses(page = 1) {
        fetch(`/houses?page=${page}&limit=${pageSize}`)
            .then(response => response.json())
            .then(data => {
                const houseList = document.getElementById('houseList').getElementsByTagName('tbody')[0];
                houseList.innerHTML = '';  // 清空当前列表
                data.houses.forEach(house => {
                    const row = houseList.insertRow();
                    row.innerHTML = `
                            <td>${house.id}</td>
                            <td>${house.title}</td>
                            <td>${house.rooms}</td>
                            <td>${house.area}</td>
                            <td>${house.price}</td>
                            <td>${house.address}</td>
                            <td>
                                <button onclick="editHouse(${house.id})">编辑</button>
                                <button class="delete" onclick="deleteHouse(${house.id})">删除</button>
                            </td>
                        `;
                });

                // 渲染分页
                renderPagination(data.totalPages, page);
            })
            .catch(error => console.error('获取房源失败:', error));
    }

    // 渲染分页
    function renderPagination(totalPages, currentPage) {
        const paginationContainer = document.getElementById('pagination');
        paginationContainer.innerHTML = '';

        const prevButton = document.createElement('button');
        prevButton.innerText = '上一页';
        prevButton.disabled = currentPage <= 1;
        prevButton.onclick = () => {
            if (currentPage > 1) {
                getHouses(currentPage - 1);
            }
        };
        paginationContainer.appendChild(prevButton);

        for (let i = 1; i <= totalPages; i++) {
            const pageButton = document.createElement('button');
            pageButton.innerText = i;
            pageButton.disabled = i === currentPage;
            pageButton.onclick = () => getHouses(i);
            paginationContainer.appendChild(pageButton);
        }

        const nextButton = document.createElement('button');
        nextButton.innerText = '下一页';
        nextButton.disabled = currentPage >= totalPages;
        nextButton.onclick = () => {
            if (currentPage < totalPages) {
                getHouses(currentPage + 1);
            }
        };
        paginationContainer.appendChild(nextButton);
    }

    // 添加/更新房源
    document.getElementById('addHouseForm').addEventListener('submit', function (event) {
        event.preventDefault();
        const formData = new FormData(event.target);
        const data = {};
        formData.forEach((value, key) => data[key] = value);

        const houseId = document.getElementById('houseId').value;

        // 判断是添加房源还是更新房源
        const url = houseId ? `/update_house/${houseId}` : '/add_house';
        const method = houseId ? 'PUT' : 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
            .then(response => response.json())
            .then(result => {
                alert(result.message);
                getHouses(currentPage);  // 重新加载当前页房源列表
                resetForm();  // 重置表单
            })
            .catch(error => console.error('操作失败:', error));
    });

    // 编辑房源
    function editHouse(id) {
        fetch(`/house/${id}`)
            .then(response => response.json())
            .then(house => {
                document.getElementById('formTitle').innerText = '编辑房源';
                document.getElementById('houseId').value = house.id;
                document.getElementById('title').value = house.title;
                document.getElementById('rooms').value = house.rooms;
                document.getElementById('area').value = house.area;
                document.getElementById('price').value = house.price;
                document.getElementById('address').value = house.address;
            })
            .catch(error => console.error('获取房源信息失败:', error));
    }

    // 删除房源
    function deleteHouse(id) {
        if (confirm('确认删除该房源吗？')) {
            fetch(`/delete_house/${id}`, {
                method: 'DELETE',
            })
                .then(response => response.json())
                .then(result => {
                    alert(result.message);
                    getHouses(currentPage);  // 重新加载当前页房源列表
                })
                .catch(error => console.error('删除房源失败:', error));
        }
    }

    // 重置表单
    function resetForm() {
        document.getElementById('addHouseForm').reset();
        document.getElementById('houseId').value = '';
        document.getElementById('formTitle').innerText = '添加房源';
    }

    // 初始化加载房源列表
    getHouses(currentPage);
</script>

</body>
</html>
